const jwtDecode = require("../module/jwt-decode");
const notification = require('./notification.js');
const tokenKey = 'userToken';
const tokenInfoKey = tokenKey + 'Decodeinfo';
const authutil = {
  /**
   * 对状态进行判断
   */
  checkStatus(status) {
    if (status == '401') {
      wx.clearStorageSync(tokenKey);
      wx.clearStorageSync(tokenInfoKey);
      wx.clearStorageSync("baseUserInfo");
      wx.reLaunch({
        url: '/pages/auth/login/index'
      })
    } else if (status == '403') {
      wx.clearStorageSync(tokenKey);
      wx.clearStorageSync(tokenInfoKey);
      wx.clearStorageSync("baseUserInfo");
      wx.reLaunch({
        url: '/pages/auth/login/index'
      })
    }
  },
  toIndex() {
    let userTokenInfo = authutil.getTokenInfo();
    console.log("token信息", userTokenInfo);
    if (userTokenInfo.user_type == "01") {
      //会员
      wx.reLaunch({
        url: '/pages/home/index',
      })
    } else if (userTokenInfo.user_type == "02") {
      //管理员
      wx.reLaunch({
        url: '/pages/admin/home/index',
      })
    }
  },
  /**
   * 退出登录
   */
  logout() {
    wx.showModal({
      title: '提示',
      content: '确定退出吗？',
      confirmColor: '#E50012',
      success(res) {
        if (res.confirm) {
          wx.clearStorageSync(tokenKey);
          wx.clearStorageSync(tokenInfoKey);
          wx.clearStorageSync("baseUserInfo");
          wx.reLaunch({
            url: '/pages/auth/login/index'
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
  /**
   * 判断用户是否登录
   * baseType  用户类型
   * key token的键值
   * reLaunch  是否自动跳转到登录页面
   */
  isLogin(reLaunch) {
    let decodeinfo = authutil.getTokenInfo(tokenInfoKey);
    if (decodeinfo != null) {
      //已经拥有的token与当前用户身份匹配
      let nowTime = Date.now() / 1000;
      if (nowTime < decodeinfo.exp) {
        return true;
      } else {
        notification.error("登录已过期");
      }
    }
    // notification.error("未登录");
    if (reLaunch == true) {
      wx.navigateTo({
        url: '/pages/auth/login/index?user_type=' + userType
      })
    }
    return false;
  },
  getAuthToken() {
    try {
      return wx.getStorageSync(tokenKey);
    } catch (e) {
      console.info("缓存token失败");
      return null;
    }
  },
  /**
   * 把合法的token写入缓存
   */
  setAuthToken(token) {
    try {
      //token放入缓存
      wx.setStorageSync(tokenKey, token);
      //解析token信息，放入
      let decodeToken = authutil.decodeToken(token, true);
    } catch (e) {
      console.info("缓存token失败");
    }
    return null;
  },
  /**
   * 解析token信息，放入缓存
   */
  decodeToken(token, setStatus) {
    try {
      token = token || wx.getStorageSync(tokenKey);
      const decoded = jwtDecode(token);
      if (setStatus) {
        wx.setStorageSync(tokenInfoKey, decoded);
      }
      return decoded;
    } catch (e) {
      console.log("token解析异常token===", token);
      return null;
    }
  },
  /**
   * 获取token解析后的信息
   */
  getTokenInfo(key) {
    return wx.getStorageSync(tokenInfoKey) || authutil.decodeToken(null, true);
  },
  /**
   * 用于验证用户的信息
   */
  checkAuth(repData) {
    console.log("正在验证用户身份", repData.statusCode);
  },
  setWxUserinfo(wxUserInfo) {
    if (wxUserInfo) {
      wx.setStorageSync("wxUserInfo", wxUserInfo);
    } else {
      wx.getSetting({
        success(res) {
          if (res.authSetting['scope.userInfo']) {
            // 已经授权，可以直接调用 getUserInfo 获取头像昵称
            wx.getUserInfo({
              success: function(res) {
                console.log("获取微信用户信息成功", res.userInfo);
                wx.setStorageSync("wxUserInfo", res.userInfo);
              }
            })
          }
        }
      })
    }
  },
  getWxUserinfo() {
    return wx.getStorageSync("wxUserInfo");
  }
}
module.exports = authutil;